package com.example.orderservice.service;

import com.example.orderservice.client.AccountServiceClient;
import com.example.orderservice.client.StorageServiceClient;
import com.example.orderservice.dao.OrderMapper;
import com.example.orderservice.entity.Order;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * program: springcloud-seata
 * description:
 * author: Mr.Yiu
 * create: 2021-05-20 11:20
 **/
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    AccountServiceClient accountServiceClient;
    @Autowired
    StorageServiceClient storageServiceClient;

    public List<Order> findOrderList(){
        return orderMapper.findOrderList();
    }

    //创建订单
    @GlobalTransactional
    public Map<String, Object> createOrder(int userId, int productId, double money, int num){
        Order order = new Order();
        order.setMoney(money);
        order.setUser("felix");
        order.setId(UUID.randomUUID().toString());
        orderMapper.createdOrder(order);

        try {
            storageServiceClient.deductStorage(productId, num);

            accountServiceClient.deductMoney(userId, money);
        }catch(Exception e){
           throw new RuntimeException("异常，回滚");//异常触发回滚
        }


        return null;
    }

    public int createOrder(Order order){
        return orderMapper.createdOrder(order);
    }
}
